#ifdef _WIN32 // windows os

#include <string>
#include <stdio.h>
#include <stdlib.h>
#include "share_mem.h"

namespace anet {
	namespace SShareMemorySpace {
		bool CShareMemory::CreateShareMem(key_t key, size_t memSize) {
			if (m_pshm != nullptr) { // it has create memory?
				return true;
			}
			m_create = true;

			// try to open file mapping
			HANDLE hMap = ::OpenFileMapping(FILE_MAP_ALL_ACCESS,0,std::to_string(key).c_str());
			if (nullptr == hMap) {
				// just create file mapping if open failed.
				hMap = ::CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,(DWORD)memSize,std::to_string(key).c_str());
				if (hMap == nullptr) {
					return false;
				} else {
					// map file to get its memory.
					m_pshm = ::MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
				}
			} else {
				return false;
			}
			if (m_pshm == nullptr) {
				return false;
			}

			m_shmSize = memSize;
			m_shmId = hMap;
			m_shmKey = key;
			return true;
		}

		bool CShareMemory::OpenShareMem(key_t key, size_t memSize) {
			if (m_pshm != nullptr) { // it has create memory?
				return true;
			}
			m_create = false;

			// try to open file mapping
			HANDLE hMap = ::OpenFileMapping(FILE_MAP_ALL_ACCESS,0,std::to_string(key).c_str());
			if (hMap == nullptr) {
				return false;
			} else {
				// map file if open successfully.
				m_pshm = ::MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS,0,0,0);
			}
			if (m_pshm == nullptr) {
				return false;
			}

			m_shmSize = memSize;
			m_shmId = hMap;
			m_shmKey = key;
			return true;
		}

		int CShareMemory::Detach() {
			if (m_pshm != nullptr) {
				UnmapViewOfFile(m_pshm);
				CloseHandle(m_shmId);
				m_pshm = nullptr;
			}
			return 0;
		}

		int CShareMemory::Delete() {
			return 0;
		}
	}
}

#endif